<template>
  <main>
    <ul class="list">
      <h4 class="fullname" style="width: 100%">{{ fullName }}</h4>
      <li
        v-for="item in store.chapterList"
        @click="change(item)"
        :key="item.chapterId"
        :class="{ active: item.bible_readId }"
      >
        {{ item.section }}
      </li>
      <li class="fix"></li>
      <li class="fix"></li>
      <li class="fix"></li>
      <li class="fix"></li>
      <li class="fix"></li>
      <li class="fix"></li>
    </ul>
  </main>
</template>
<script setup>
import { ref, onMounted, watch, computed } from "vue";
import request from "../../api/request";
import { useStore } from "../../pinia";
import { storeToRefs } from "pinia";

const store = useStore();

// 获取读经数量
const getTodayReadNum = async () => {
  // let res = await request.get("/bible_read/today");
  // store.$patch(state=>{
  //   state.todayReadNum = res.data.length;
  // })
  store.getTodayReadNum();
};

const change = async (item) => {
  let data = {
    bible_userId: store.user.bible_userId,
    ...item,
  };
  let res = await request.post("/bible_read/daka", data);
  item.bible_readId = res.data.bible_readId;

  // 读了加1, 没读-1
  let readNum = item.bible_readId ? 1 : -1;
  // 修改今天的读经数量
  store.$patch((state) => {
    if (state.todayReadNum + readNum < 0) {
      state.todayReadNum = 0;
    } else {
      state.todayReadNum = state.todayReadNum + readNum;
    }
    if (state.weekReadNum + readNum < 0) {
      state.weekReadNum = 0;
    } else {
      state.weekReadNum = state.weekReadNum + readNum;
    }
  });

  // 找到对应的书本
  let index = store.bookList.findIndex((book) => book.name === item.name);
  store.$patch((state) => {
    let book = state.bookList[index];
    state.bookList[index].haveRead = book.haveRead + readNum;
    if (!book.haveRead) {
      book.readStatus = 3;
    } else {
      if (book.haveRead === book.num) {
        book.readStatus = 1;
      } else {
        book.readStatus = 2;
      }
    }
  });
};

let fullName = computed(() => {
  let book = store.bookList.find((item) => item.name === store.currBook);
  return book.fullName;
});

let { currBook } = storeToRefs(store);
// watch(currBook, (value) => {
//   store.getChapterList();
// });

const getList = async () => {
  store.getChapterList();
  // let res = await request.get("/bible_chapter/list?name=" + currBook.value);
  // store.$patch(state=> {
  //   state.chapterList = res.data;
  // })
};
onMounted(() => {
  store.getChapterList(store.currBook);
  getTodayReadNum();
});
</script>

<style>
.fullname {
  text-align: center;
  line-height: 50px;
}
</style>
